import requests
from requests.exceptions import RequestException  #引入捕获异常包
from multiprocessing import Pool   # 多进程包实现秒抓
import re
import json

# 有反爬机制需要加headers
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36',
    'Cookie': 'uuid_n_v=v1; uuid=4D8AAE7088E611E8AFB511FE4A2E3FDCEF51B4443E574BFE9EDF4D4CEBF7DD74; _csrf=d28161d74a4a2573c95883a472',
}
# 定义一个请求单页内容的方法
def get_one_pege(url):
    try:
        # 发起请求
        response=requests.get(url,headers=headers)
        # 判断是否请求成功
        if response.status_code ==200:
            # 成功返回页面内容
            return response.text
        #异常返回None
    except RequestException:
        return None

def parse_one_page(html):
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
                         +'.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
                          +'.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',re.S)
    items = re.findall(pattern,html)
    for item in items:
        yield {
            'index':item[0],
            'image':item[1],
            'title':item[2],
            'actor':item[3].strip()[3:],
            'time':item[4].strip()[5:],
            'score':item[5]+item[6]
        }
def write_to_file(content):
    with open('maoyan.txt','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False) + '\n',)
        f.close()


def main(offset):
    url = 'http://maoyan.com/board/4?offset='+ str(offset)
    html = get_one_pege(url)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)

if __name__ == '__main__':
    # #单进程
    # for i in range(10):
    #     main(i*10)
    # 多进程
    pool = Pool()
    '''
    map方法将数组中的每一个元素拿出来,当作函数的参数,然后去创建每一个进程放进进程池当中去运行
    '''
    pool.map(main,[i*10 for i in range(10)])
    pool.close()
    pool.join()



